package cn.fate.core.adaper;

import cn.fate.core.common.JsonUtil;
import cn.fate.core.common.RedisUtil;
import cn.fate.core.common.ResponseBean;
import cn.fate.core.common.StringUtil;
import cn.fate.core.dao.basic.entity.Staff;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @program: FtCore
 * @description:
 * @author: xubo
 * @create: 2021-09-14 14:32
 **/
public class CheckLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    public CheckLoginInterceptor() {
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Token");
        if (!StringUtil.isNullOrEmpty(token) && this.redisUtil.getToken(token, Staff.class) != null) {
            return true;
        } else {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            String rspJson = JsonUtil.toStr(ResponseBean.failWithMessage("请先登录"));
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            out = response.getWriter();
            out.append(rspJson);
            out.close();
            return false;
        }
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
